String.prototype.trim=function(){
	return this.replace(/^\s*|\s*$/g, "");
};
var STATUS_CONFLICT = "conflict";
var STATUS_REMOVE = "removed";
var STATUS_OK = "ok";
var STATUS_NOAUTHORITY = "noauthority";
var STATUS_MEMBER_CONFLICT = "memconflict";
$(document).ready(function() {
	$("#set-option").unbind("click");
					
	displayLang = $("#display-lang").val();
	Etype = $("#etype").val();
	Eid = $("#eid").val();
	Genre = $("#genre").val();
	Gid = $("#gid").val();
	Gname = $("#gname").val();
	//一个推荐实体理由条目默认显示数目
	initCount = 5;
	//每种推荐每页显示数目
	recomdNum = 5;
	
	//back to entity browsing
	$("a.back").click(function(){
		var location = WEBAPP+"entity/"+Genre+Eid+"?lang="+displayLang;
		window.location= location;
	});
	
	$(".edit-save .cbutton").click(function(){
		var location = WEBAPP+"entity/"+Genre+Eid+"?lang="+displayLang;
		window.location= location;
	});
	
    /*navigation tabs*/
	$(".section>.tab-header").click(function(){
		$(this).parent().children(".content").toggle();
		$(this).find(".tab-status").toggleClass("down");
	});
	
/*start:init*/
	init();
/*end:init*/
	
/*start: has create custom entity */
	$(".changeBox input.no").click(function(){
		var location = WEBAPP+"entity/"+Genre+Eid+"?lang="+displayLang;
		window.location= location;
	});
	
	$(".changeBox input.yes").click(function(){
	    var meid = $(this).parent().parent().find(".ename").attr("eid");
	    var location = "/sview/views/identity.jsp?genre="
	    	+CUSTOM_ENTITY_STR+"&lang="+displayLang+"&eid="+meid;
		window.location =location;
	});	
/*end: has create custom entity*/

/*start:image operation*/
	$("a.addImage").click(function(){
		$("#imgURI").val("http://");
		$("#image-op").dialog({
			 modal:true,
			 width:700
		});
		return false;		
	});
	
	$("#imgURI").focus(function(){
		$(this).parent().parent().find(".error").hide();
	});
	
	/*upload image*/
	$(".upload-btn a").click(function(){
		var hints = $("#image-op .error").text("");
		hints.hide();
		var value = $("#imgURI").val().trim();
		if(value==""||value=="http://"){
			var textEn = "Please enter the URI";
			var textZhSimple ="请输入URI";
			if(displayLang=="en")
				hints.html(textEn);
			else if(displayLang=="zh")
				hints.html(textZhSimple);
			hints.show();
			return false;
		}
		
		addImageInPage(value);
        
        $("#image-op").dialog("close");
        
        return false;
	});
	
	$(".imgBox").live("mouseover",function(){
		$(this).find("a.imgDelete").show();
	});
	
	$(".imgBox").live("mouseout",function(){
		$(this).find("a.imgDelete").hide();
	});	
	
	$("a.imgDelete").live("click",function(){
	  	var title ;
    	var msg;
    	if(displayLang=="en"){
    		title="Warning";
    		msg = "Are you sure to delete this image?";
    	}else if(displayLang=="zh"){
    		$.messager.defaults = {ok:"确定",cancel:"取消"};
    		title="警告";
    		msg = "您确定要删除它吗?";
    	}
    	var element = $(this);
	    $.messager.confirm(title, msg,function (data) {
		  if (data) {
			if(!$(".image").hasClass("changed")){
				$(".image").addClass("changed");
			}
			
			if(element.parent().hasClass("new")){
				element.parent().remove();
			}else{
				element.parent().find("img").appendTo(".imgRemoved");
				element.parent().remove();
			}
		 }
		 $.messager.defaults = {ok:"Ok",cancel:"Cancel"};
	   });
	});
/*end:image operation*/

	$("a.cancel_mem_button").live(
			"click",
			function() {
				var box = $(this).parent().parent().parent()
										.parent();
				box.find(".ebody .uriBox .content").html(box.find(".old").html());
	});

					$(".add-uri-op").live("mouseover", function() {
						$(this).addClass("hover");
					});

					$(".add-uri-op").live("mouseout", function() {
						$(this).removeClass("hover");
					});
					
					/* end:init :show the exist entity in the left nav */

					/* uri memember operation */
					$(".leftPanel .content .item").live("mouseover", function() {
						$(this).addClass("bh");
						$(this).find(".opBox").show();

					});

					$(".leftPanel .content .item").live("mouseout", function() {
						$(this).removeClass("bh");
						$(this).find(".opBox").hide();

					});

					$(".rmBox").live("click", function() {
						var link = $(this).parent().find(".link");
						var cplink = link.clone();
						var uid = link.attr("uid");
						$(this).parent().remove();
						$(".lentity .uriBox .item:last").addClass("last");
                        
                        //让右侧移除的和推荐 uri面板中相应内容又可以加入
                        $(".recommendSection").find(".add-uri-op[uid="+uid+"]").removeClass("disabled");
                       
                        //在右侧移除面板中加入新的被移除的内容
                        var removedBox = $("#tabs-removed .entityList");
                        if(removedBox.find("a[uid="+uid+"]").length==0){
                        	var item = $("<div class='item'></div>");
                        	removedBox.append(item);
                         	var op = $("<span class='add-uri-op origin-op'><span></span></span>");
         					if(displayLang=="en"){
         						op.find("span").html("Add it");
         					}else if(displayLang=="zh"){
         						op.find("span").html("加入");
         					}
         					op.attr("uid",uid);
         					item.append(cplink);
         					item.append(op);
                        }
					});
					
					//start:手动提交uri

					$(".advancedSwitch").click(function(){
						$(this).parent().find(".content").toggle();
						$(this).toggleClass("down");
					});
					
					$(".rstbtn").click(function(){
						$("#uriAdded").val("http://");
						$(this).parent().parent().find(".valid").html("");
						$(this).parent().parent().find(".sts").hide();
					});
					
					$(".addbtn").click(function(){
						var link = $("#uriAdded").val().trim();
						if (link.indexOf("http://") != 0) {
							if (displayLang == "en")
								$.messager
										.alert(
												'Error',
												'Your input uri is invalid! It must start with "http://"',
												'error');
							else if (displayLang == "zh")
								$.messager.alert('错误',
										'输入的 URI 格式错误! 必须以http://开头',
										'error');
							return;
						}
						$(this).attr("disabled",true);
						$(".rstbtn").attr("disabled",true);
						var box = $(this).parent().parent();
						box.find(".sts").hide();
						box.find(".wait").show();
						
						hasRDFDesc(link,box);
						
					});
					
					//end:手动提交uri
					
					/* end:uri memember operation */

					/* save entity */
					$(".edit-save .sbutton")
							.live(
									"click",
									function() {
										var ancestor = $(".lentity");
										var etype = ancestor.attr("etype");
										var eid = ancestor.attr("eid");
										var entityName = $(
												"input.inename")
												.val();
										if(entityName.trim()==""){
											if (displayLang == "en")
												$.messager
														.alert(
																'Error',
																'Please input the entity name!',
																'error');
											else if (displayLang == "zh")
												$.messager.alert('错误',
														'请输入实体名称!', 'error');
											return;
										}else if($(".lentity .item .info").length>0){
											scrollTop($(".lentity .item .info").parent());
											return;
										}
										
										var comment= null;
										if(isCreate()){
											if($(".commentarea").val().trim()!="")
												comment = $(".commentarea").val().trim();
										}else{
											if($(".commentarea").hasClass("changed")){
												comment = $(".commentarea").val().trim();
											}
										}
										
										var imgAddArray = new Array();
										var imgDelArray = new Array();
										
										if(!isCreate()){
											$(".image .imgRemoved img").each(function(){
											var imgID = $(this).attr("id");
											imgDelArray.push(imgID);
											});
											$(".image .imgList .imgBox.new").each(function(){
												var imgURL = $(this).find("img").attr("src");
												imgAddArray.push(imgURL);
											});
										}else{
											$(".image .imgList .imgBox").each(function(){
												var imgURL = $(this).find("img").attr("src");
												imgAddArray.push(imgURL);
											});
										}
										
										var array = new Array();
										ancestor.find(".uriBox .item").each(
												function() {
													var uid = $(this).find("a.link")
															.attr("uid");
													array.push(uid);
										});
										
										var result = saveEntity(entityName,
												etype, eid, array, comment,imgAddArray,imgDelArray);
										var status = result["status"];
										if (status ==STATUS_CONFLICT) {
											if (displayLang == "en")
												$.messager
														.alert(
																'Error',
																'The entity name has existed!',
																'error');
											else if (displayLang == "zh")
												$.messager.alert('错误',
														'实体名称已存在!', 'error');
											return;
										}else if(status ==STATUS_REMOVE ){
							    			if(displayLang=="en"){
							    				$.messager.alert('Error','Sorry. The entity has been removed elsewhere!','error');
							    			}else if(displayLang=="zh"){
							    				$.messager.alert('错误','抱歉，该实体在别处已被删除!','error');
							    			}
							    			var location = WEBAPP+"entity/"+Genre+Eid+"?lang="+displayLang;
							    			window.location= location;
							    			return ;
							    	   }else if(status ==STATUS_NOAUTHORITY ){
							   			    if(displayLang=="en"){
											   $.messager.alert('Info','The entity is being edited elsewhere. Please retry later!','info');
										    }else if(displayLang=="zh"){
											   $.messager.alert('提示','实体在别处正被编辑。请稍后再试!','info');
										    }
										    return ;
								        }else if(status==STATUS_MEMBER_CONFLICT){
								        	 var uid = result.conflictUID;
		                                	 var entity = result.conflictEntity;
		                                	 var etype  = entity.etype;
		                                	 var eid = entity.eid;
		                                	 var ename = entity.name;
		                                	    
		                                	 var conflictitem = $("a.link[uid="+uid+"]").parent();
		                                	 conflictitem.addClass("conflict");
		                                	 var div = $("<div class='info'></div>");
		                                	 conflictitem.append(div);
		                                	 var html;
		                                	 if(displayLang=="en"){
		                                	    	html = 'Your editing group has created the custom entity '+ename+
		                                	    	  ' on this uri. You can click <a href="javascript:void(0)">here</a> to edit that custom entity. Or '+
		                                	    	'you must delete this uri';
		                                	 }else if(displayLang=='zh'){
		                                	    	html = '你的编辑组已经在这个 uri 上创建了自定义实体 '+ename+
		                                	    	  '. 你可以点击 <a href="javascript:void(0)">这里</a>来编辑那个自定义实体. 或者你须要删除这个 uri';
		                                	 }
		                                	 div.html(html);
		                                	  div.find("a").click(function(){
		                                	    	var location = "/sview/views/identity.jsp?genre="
		                         					   +CUSTOM_ENTITY_STR+"&lang="+displayLang+"&eid="+eid;
		                         				    window.location =location;
		                                	  });
		                                	  scrollTop(conflictitem);
								        }
									    else if(status==STATUS_OK){
											var resType = result.entityType;
											var resID = result.entityID;
											ancestor.attr("etype", resType);
											ancestor.attr("eid", resID);
											
											if(isCreate()){
											  $(".container").html("");
											  var box = $("<div class='switchBox'></div>");
											  $(".container").append(box);
											  var infodiv = $("<div></div>");
											  box.append(infodiv);
											  if(displayLang=="en"){
												infodiv.html("Entity is created successfully! Go to visit the newly created custom entity now?");
											  }else if(displayLang="zh"){
												infodiv.html("创建成功。现在去访问新创建的自定义实体吗?");
											  }
											
											  var ops ;
											  if(displayLang=="en"){
												ops =$('<div class="op"><input type="button" class="yes" value="Yes" /> <input type="button" class="no" value="No" /></div>');
											  }else{
												ops= $('<div class="op"><input type="button" class="yes" value="好的" /> <input type="button" class="no" value="以后再说" /></div>');
											  }
											  box.append(ops);
											
											  ops.find("input.yes").click(function(){
												var location = WEBAPP+"entity/e"+resID+"?lang="+displayLang;
				                        		window.location= location;
											  });
											
											  ops.find("input.no").click(function(){
												var location = WEBAPP+"entity/"+Genre+Eid+"?lang="+displayLang;
				                        		window.location= location;
											  });
											}else{
												var location = WEBAPP+"entity/"+Genre+Eid+"?lang="+displayLang;
				                        		window.location= location;
											}
										}
									});
					/* end:save entity */
					
					/* recommend */
					$(".moreLess a.more").live("click", function() {
						$(this).parent().parent().find(".hidden").show();
						$(this).parent().find("a").removeClass("more");
						$(this).parent().find("a").addClass("less");
						if(displayLang=="en")
							$(this).parent().find("a").html("Less-");
						else if(displayLang=="zh")
							$(this).parent().find("a").html("更少-");
					});

					$(".moreLess a.less").live("click", function() {
						$(this).parent().parent().find(".hidden").hide();
						$(this).parent().find("a").removeClass("less");
						$(this).parent().find("a").addClass("more");
						if(displayLang=="en")
							$(this).parent().find("a").html("More+");
						else if(displayLang=="zh")
							$(this).parent().find("a").html("更多+");
					});

					$(".add-uri-op").live("click", function() {
						if($(this).hasClass("disabled"))
							return false;
						if ($(".entity-list .lentity").length == 0)
							return false;
						
						var link ;
						if(!$(this).hasClass("origin-op")){
							var box =  $(this).parent().find("h3 a");
							link = box.attr("title");
							
						}else{
							link = $(this).parent().find(".link").attr("title");
						}
						
						if($(this).hasClass("input")){
							//对于手动提交的uri
							var box = $(this).parent().parent();
							if(displayLang=="en"){
								box.html("OK.");
							}else if(displayLang=="zh"){
								box.html("完成.");
							}
							setTimeout(function(){
								box.hide();
							},1200);
						}
						
						var res = checkMemberByURI(link);
						
						addMember(link,res.linkID,res.uri, res.label, res.entity,this);

					});
					
					//falcon object search
					$("#searchq").click(function(){
						var value = $("#query").val().trim();
						getFalconSearchEntity(value, displayLang,0,recomdNum,1);
						
					});
					
					$("#query").bind("keyup",function(event){
						if (event.keyCode=="13"){
							var value = $("#query").val().trim();
							getFalconSearchEntity(value, displayLang,0,recomdNum,1);
						}
					});
					
					/* end:recommend */
});

function addImageInPage(path){
	var box = $(".image .imgList");
	var imgBox = $("<div class='imgBox'></div>");
	box.append(imgBox);
	imgBox.addClass("new");
	var imgContainer = $('<div class="img-container"></div>');
	imgBox.append(imgContainer);
	var img = $("<img />");
	img.attr("src",path);
	if(displayLang=="en"){
		img.attr("alt","load image failure");
	}else if(displayLang=="zh"){
		img.attr("alt","载入图片失败");
	}
	imgContainer.append(img);
	var adelete = $('<a class="imgDelete"><span class="img-delete"></span></a>');
	imgBox.append(adelete);
	
	if(!$(".image").hasClass("changed")){
		$(".image").addClass("changed");
	}
}

function addMember(link,linkID, uri, label, entityArray,element) {
	var ancestor = $(".lentity");
	var ances_etype = ancestor.attr("etype");
	var ances_eid = ancestor.attr("eid");
	if (ancestor.find(".uriBox a[uid=" + linkID + "]").length > 0) {
		var hints = $("<div class='hints'></div>");
		if(displayLang=="en"){
			hints.html('This URI has already been a mememer.');
		}else if(displayLang=="zh")
			hints.html('这个 URI 已经是成员.');
		hints.appendTo($(".entity-list")).show("fold");
		setTimeout(function() {
			$(".hints").fadeIn(1000);
			$(".hints").remove();
		}, 1000);
	    
		return;
	}
	
	var etype = null, eid = null, ename = null;
	for (i = 0; i < entityArray.length; i++) {
		var item = entityArray[i];
		if (item.etype != ances_etype || item.eid != ances_eid) {
			etype = item.etype;
			eid = item.eid;
			ename = item.name;
			break;
		}
	}
	if (etype != null) {
		var dialog = $(".warning");
		dialog.find(".ename").html(ename);
		var dialog_title;
		if (displayLang == "en") {
			dialog_title = "Warning";
		} else if (displayLang == "zh") {
			dialog_title = "警告";
		}
		dialog.show();
		
		var buttonJSON;
		if(displayLang=="en"){
			buttonJSON ={
				"Yes": function() {
					dialog.dialog('close');
					var location = "/sview/views/identity.jsp?genre="
					   +CUSTOM_ENTITY_STR+"&lang="+displayLang+"&eid="+eid;
				    window.location =location;
			  },
			    "No":function() {
			    	dialog.dialog('close');
			  }
			};
		}else if(displayLang=="zh"){
			buttonJSON ={
				 "是": function() {
						dialog.dialog('close');
						var location = "/sview/views/identity.jsp?genre="
							   +CUSTOM_ENTITY_STR+"&lang="+displayLang+"&eid="+eid;
						    window.location =location;
				 },
				  "否":function() {
				    	dialog.dialog('close');
				 }
		    };			
		}
			
		dialog.dialog({
			title : dialog_title,
			modal : true,
			width : 500,
			buttons:buttonJSON
		});
	}else{
		$(".lentity .uriBox .content .item:last").removeClass("last");
		var container = $("<div class='item'></div>");
		$(".lentity .uriBox .content").append(container);
		
		var linkBox = $("<a target='_blank' class='link'></a>").html(link);
		linkBox.attr("uid", linkID);
		var href = WEBAPP+"entity/o" + linkID+"?lang="+displayLang;
		linkBox.attr("href", href);
		linkBox.attr("title", uri);
		linkBox.html(label);
		container.append(linkBox);
		var rmBox = $("<a class='opBox rmBox' href='javascript:void(0)'><span class='rm_box'></span></a>");
		if(displayLang=="en"){
			rmBox.attr("title",'Remove this URI');
		}else if(displayLang=="zh"){
			rmBox.attr("title",'删除这个URI');
		}
		container.append(rmBox);
		var uriDiv = $("<div class='uri'></div>").html(uri);
		container.append(uriDiv);
		$(".lentity .uriBox .content .item:last").addClass("last");
		
		$(".recommendSection").find(".add-uri-op[uid="+linkID+"]").addClass("disabled");
		if(!$(element).hasClass("origin-op")){
			//删除移除面板中相同的内容
			$("#tabs-removed").find(".add-uri-op[uid="+linkID+"]").parent().remove();
		}else{
			//对于移除面板中的内容，加入后就删除
			$(element).parent().remove();
		}
	}
}

function checkMemberByURI(link) {
	var result;
	var data = {};
	data["groupID"] = Gid;
	data["link"] = link;
	data["lang"] = displayLang;

	data = JSON.stringify(data);
	data = ("checkmemURI=" + encodeURIComponent(data));

	$.ajax({
		url:ENTSERV,
		async : false,
		data : data,
		dataType : "json",
		type : "post",
		success : function(data) {
			result = data;
		}
	});
	return result;
}

function recommend(){
	var start = 0;
	getRecommendCorefEntity(Gid, Etype, Eid, displayLang,start,recomdNum,1);
	
	var query = "";
	var num =$(".uriBox .item a.link").length;
	var count =0;
	$(".uriBox .item a.link").each(function(){
		count++;
		var html = $(this).html();
		var regExp =/~/g;
		html = html.replace(regExp,"");
		query = query+html;
		if(count!=num)
			query = query+" or ";
		
	});
	$("#query").val(query);
	if(query.trim()!=""){
		getFalconSearchEntity(query,displayLang,start,recomdNum,1);
	}
}

function createEditEntityBox(name, etype, eid, gname, entityType, entityID) {
	var list = $(".leftPanel .entity-list").html("");
	var lentity = $('<div class="lentity"></div>');
	list.append(lentity);
	lentity.attr("etype",etype);
	lentity.attr("eid",eid);
	var vbody = $('<div class="ebody"></div>');
	lentity.append(vbody);
	
	var uriBox ;
	uriBox= createNewURIBox(etype, eid);
	vbody.append(uriBox);
	getMembers(uriBox.find(".content"), etype, eid, "l", entityType, entityID);
}

function createRecommendEntityBox(uriID, uri, label, typeArray,snippet,outerBox) {
	var rentity = $('<li class="rentity"></li>');
	outerBox.append(rentity);
	var addOp = $("<span class='add-uri-op'></span>");
	var addOplabel = $("<span></span>");
	addOp.append(addOplabel);
	addOp.attr("uid",uriID);
	if (displayLang == "en") {
		addOplabel.html("Add it");
	} else if (displayLang == "zh") {
		addOplabel.html("加入");
	}
	if($(".uriBox a[uid="+uriID+"]").length>0){
		addOp.addClass("disabled");
	}
	rentity.append(addOp);
	var titleDiv = $("<div class='title'></div>");
	rentity.append(titleDiv);
	var h3 = $("<h3></h3>");
	titleDiv.append(h3);
	var titleLink = $("<a target='_blank'></a>").html(label);
	var href = WEBAPP+"entity/o" + uriID+"?lang="+displayLang;
	titleLink.attr("href", href);
	titleLink.attr("title", uri);
	titleLink.attr("uid",uriID);
	h3.append(titleLink);

	if(typeArray.length>0){
		var typeBox = $("<div class='typeBox'><span class='pc'>is a</span></div>");
		rentity.append(typeBox);
		var maxTypeNum = 11;
		for (i = 0; i < typeArray.length; i++) {
			var typeItem = typeArray[i];
			var span = $("<span></span>");
			span.html(typeItem.label);
			span.attr("cid", typeItem.id);
			typeBox.append(span);
			if (i != typeArray.length - 1) {
				var label = $("<label> , </label>");
				typeBox.append(label);
			}
			if(i==maxTypeNum&&i<typeArray.length-1){
				var mspan = $("<span>...</span>");
				typeBox.append(mspan);
				break;
			}
		}
	}

	var contentDiv = $("<div class='content'></div>");
	rentity.append(contentDiv);
	var proofList = $("<div class='proofList'></div>");
	contentDiv.append(proofList);
	var count = 0;
	var box = proofList;
	for (i = 0; i < snippet.length; i++) {
		var triple = snippet[i];
		
		count++;
		if (count == initCount + 1) {
			var hidden = $("<div class='hidden'></div>");
			proofList.append(hidden);
			box = hidden;
		}
		
		var pitem = $("<div class='pitem'></div>");
		box.append(pitem);
		for(j=0;j<triple.length;j++){
			var resource = triple[j];
			var type = resource.type;
		    var span = $("<span></span>");
		    if(j==1)
		    	span.addClass("property");
		    pitem.append(span);
		    if(type=="l"){
		    	span.html(resource.label);
		    }else if(type=="u"){
		    	var id = resource.id;
		    	var uri = resource.uri;
		    	var label = resource.label;
		    	
		    	if(resource.directuri==1){
		    		var alink = $("<a target='_blank'></a>").html(uri);
			    	alink.attr("href",uri);
			    	alink.attr("title",uri);
			    	alink.addClass("directlink");
		    	}else{
		    		var alink = $("<a target='_blank'></a>").html(label);
			    	alink.attr("uid",id);
			    	var href = "/sview/entity/o"+id+"?lang="+displayLang;
			    	alink.attr("href",href);
			    	alink.attr("title",uri);
		    	}
		    
		    	span.append(alink);
		    }
		}
	}

	if (count >initCount) {
		var moreDiv = $("<div class='moreLess'><a class='more' href='javascript:void(0)'></a></div>");
		if(displayLang=="en"){
			moreDiv.find("a").html("More+");
		}else if(displayLang=="zh"){
			moreDiv.find("a").html("更多+");
		}
		proofList.append(moreDiv);
	}
}

function createInfoToolBar(gname) {
	var toolbar = $('<div class="tool_bar_info"></div>');
	var ginfo = $('<div class="group_info"></div>');
	toolbar.append(ginfo);
	var label = $("<label></label>");
	if(displayLang=="en")
		label.html("By group");
	else if(displayLang=="zh")
		label.html("属于组");
	ginfo.append(label);
	var span = $('<span class="gname"></span>').html(gname);
	ginfo.append(span);
	return toolbar;
}

function createRightURIBox(etype, eid) {
	var box = $('<div class="uriBox"></div>');
	var toolbar = $('<div class="tool_bar"></div>');
	box.append(toolbar);
	var label = $("<label class='title'>URIs</label>");
	toolbar.append(label);
	var tools = $("<div class='tools'></div>");
	toolbar.append(tools);
	var alink = $('<a href="javascript:void(0)" class="easyui-linkbutton add_op"'
			+ '	iconCls="icon-addAll" plain="true" ></a>');
	if (displayLang == "en") {
		alink.attr("title",
				"Add all the URIs of this entity to the entity of my group");
	} else if (displayLang == "zh") {
		alink.attr("title", "向我的组的实体中加入所有的URI");
	}
	tools.append(alink);
	alink.linkbutton();
	var content = $('<div class="content"></div>');
	box.append(content);

	return box;
}

function createNewURIBox(etype, eid) {
	var box = $('<div class="uriBox"></div>');
	var toolbar = $('<div class="tool_bar"></div>');
	box.append(toolbar);
	var label = $("<label class='title'>URIs</label>");
	toolbar.append(label);
	var tools = $("<div class='tools'></div>");
	toolbar.append(tools);
	var content = $('<div class="content"></div>');
	box.append(content);

	return box;
}

function getCustomEntityName(etype, eid) {
	var data = {};
	data["etype"] = etype;
	data["eid"] = eid;

	data = JSON.stringify(data);
	data =( "cename=" + encodeURIComponent(data));

	$.ajax({
		url: ENTSERV,
		async : true,
		data : data,
		dataType : "text",
		type : "post",
		success : function(result) {
			for (i = 0; i < result.length; i++) {
				var item = result[i];
				var name = item.name;
				var etype = item.etype;
				var eid = item.eid;
				var gid = item.gid;
				var gname = item.gname;
				var li = $("<li></li>");
				$(".leftnav").append(li);
				var a = $("<a class='nav-item' href='javascript:void(0)'></a>")
						.html(name);
				a.attr("etype", etype);
				a.attr("eid", eid);
				a.attr("gid", gid);
				a.attr('gname', gname);
				li.append(a);
			}
		}
	});
}

function getMembers(box, etype, eid, pos, entityType, entityID) {
	var data = {};
	data["etype"] = etype;
	data["lang"] = displayLang;
	data["eid"] = eid;
	data["groupID"] = Gid;
	if (entityType) {
		data["s_etype"] = entityType;
		data["s_eid"] = entityID;
	}
	data = JSON.stringify(data);
	data = ("gmem=" + encodeURIComponent(data));
	$.ajax({
		url: ENTSERV,
		async : false,
		data : data,
		dataType : "json",
		type : "post",
		success : function(result) {
			box.html("");
			for (i = 0; i < result.length; i++) {
				var item = result[i];
				var uriID = item.uriID;
				var uri = item.uri;
				var label = item.label;
				var isExist = item.isExist;
				if(pos == "l"&&(isExist==1))
					continue;
				var div = $("<div class='item'></div>");
				box.append(div);
				var alink = $('<a  target="_blank" class="link"></a>').html(label);
				var href = WEBAPP+"entity/o" + uriID+"?lang="+displayLang;
				alink.attr("href", href);
				alink.attr("uid", uriID);
				alink.attr("title", uri);
				div.append(alink);
				var op;
				if (pos == "l") {
					op = $("<a class='opBox rmBox' href='javascript:void(0)'>"
							+ "<span class='rm_box'></span></a>");
					if (displayLang == "en") {
						op.attr("title", "Remove this URI");
					} else if (displayLang == "zh") {
						op.attr("title", "删除这个URI");
					}
				}
//				else if (pos == "r") {
//					op = $("<span class='add-uri-op origin-op'><span></span></span>");
//					if(displayLang=="en"){
//						op.find("span").html("Add it");
//					}else if(displayLang=="zh"){
//						op.find("span").html("加入");
//					}
//					if(isExist==0){
//						op.addClass("disabled");
//					}
//				}
				var uriDiv = $("<div class='uri'></div>").html(uri);
				div.append(uriDiv);
				div.append(op);
			}
			box.find(".item:last").addClass("last");
			
			//store the history
			if(pos=="l"){
				var ebody = box.parent().parent();
				if(ebody.find(".old").length==0){
					var oldContent = $("<div class='old'></div>");
					ebody.append(oldContent);
				}
				
				ebody.find(".old").html(box.html());
			}
		}
	});
}

function getRecommendCorefEntity(groupID, etype, eid, lang,start,length,currentPage) {
	var data = {};
	data["etype"] = etype;
	data["lang"] = displayLang;
	data["eid"] = eid;
	data["groupID"] = groupID;
	data["start"] = start;

	data = JSON.stringify(data);
	data = ("recommendCorefEntity=" + encodeURIComponent(data));
	var outBox = $("#tabs-objcoref .content ul.entityList");
	$.ajax({
		url: ENTSERV,
		async : true,
		data : data,
		dataType : "json",
		type : "post",
		beforeSend:function(){
			outBox.html("");
			var loadDiv = $("<div class='loading2'></div>");
			outBox.append(loadDiv);
		},
		success : function(data) {
			outBox.html("");
			var totalNum = data["totalNum"];
			var totalPage = Math.ceil(totalNum/length);
			var result = data["items"];
			for (k = 0; k < result.length; k++) {
				var item = result[k];
				var uriID = item.uriID;
				var uri = item.uri;
				var label = item.label;
				var typeArray = item.type;
				var snippet = item.snippet;
				createRecommendEntityBox(uriID, uri, label, typeArray,snippet,outBox);
			}
			
			//paging information
			var navDiv = $("<div class='navfoot'></div>");
			outBox.append(navDiv);
			if(currentPage>1){
				var prevaLink = $('<a  class="navContent pnnav" href="javascript:void(0)"></a>');
				prevaLink.bind("click",function(){
					var mstart = (start-length)<0?0:(start-length);
					getRecommendCorefEntity(groupID, etype, eid, lang,mstart,length,currentPage-1);
				});
				if(displayLang=='en')
					prevaLink.text("Prev");
				else if(displayLang=="zh")
					prevaLink.text("上一页");
				navDiv.append(prevaLink);
			}
			
			/*in the view paging, 5 pages shown*/
			var startPage = (currentPage-2)>0?(currentPage-2):1;
			var endPage = (currentPage+2)>totalPage?(totalPage>0?totalPage:1):(currentPage+2);
			
			if(endPage>startPage){
			for(var j=startPage;j<=endPage;j++){
				if(j!=currentPage){
					var alink =$('<a class="navContent" href="javascript:void(0)"></a>');
					alink.text(j);
					alink.click(function(){
						var pointer = parseInt($(this).text());
						getRecommendCorefEntity(groupID, etype, eid, lang,(pointer-1)*length,length,pointer);
					});
					navDiv.append(alink);
				}else{
					var span = $("<span class='navContent current' ></span>");
					span.text(j);
					navDiv.append(span);
				}
			}
			}
			if(currentPage<totalPage){
				var nextaLink = $('<a  class="navContent pnnav" href="javascript:void(0)"></a>');
				nextaLink.bind("click",function(){
					getRecommendCorefEntity(groupID, etype, eid, lang,start+length,length,currentPage+1);
				});
				if(displayLang=='en')
					nextaLink.text("Next");
				else if(displayLang=="zh")
					nextaLink.text("下一页");
				navDiv.append(nextaLink);
			}	
			
		  }
	});
}

function getFalconSearchEntity(keyword, lang,start,length,currentPage) {
	var data = {};
	data["kw"] = keyword;
	data["start"] = start;
	data["lang"] = displayLang;

	data = JSON.stringify(data);
	data = ("falconSearchEntity=" + encodeURIComponent(data));
	var outBox = $("#tabs-search .content ul.entityList");
	$.ajax({
		url: ENTSERV,
		async : true,
		data : data,
		dataType : "json",
		type : "post",
		beforeSend:function(){
			outBox.html("");
			var loadDiv = $("<div class='loading2'></div>");
			outBox.append(loadDiv);
		},
		success : function(data) {
			outBox.html("");
			var totalNum = data["totalNum"];
			var totalPage = Math.ceil(totalNum/length);
			if(totalNum==0){
				var div=$("<div style='text-align:center'></div>");
				outBox.append(div);
				if(displayLang=="en"){
					div.html("No results");
				}else if(displayLang=="zh"){
					div.html("查询结果为空");
				}
				return;
			}
			var result = data["items"];
			for (k = 0; k < result.length; k++) {
				var item = result[k];
				var uriID = item.uriID;
				var uri = item.uri;
				var label = item.label;
				var typeArray = item.type;
				var snippet = item.snippet;
				createRecommendEntityBox(uriID, uri, label, typeArray,snippet,outBox);
			}
			
			//paging information
			var navDiv = $("<div class='navfoot'></div>");
			outBox.append(navDiv);
			if(currentPage>1){
				var prevaLink = $('<a  class="navContent pnnav" href="javascript:void(0)"></a>');
				prevaLink.bind("click",function(){
					var mstart = (start-length)<0?0:(start-length);
					getFalconSearchEntity(keyword, lang,mstart,length,currentPage-1);
				});
				if(displayLang=='en')
					prevaLink.text("Prev");
				else if(displayLang=="zh")
					prevaLink.text("上一页");
				navDiv.append(prevaLink);
			}
			
			/*in the view paging, 5 pages shown*/
			var startPage = (currentPage-2)>0?(currentPage-2):1;
			var endPage = (currentPage+2)>totalPage?(totalPage>0?totalPage:1):(currentPage+2);
			
			if(endPage>startPage){
			for(var j=startPage;j<=endPage;j++){
				if(j!=currentPage){
					var alink =$('<a class="navContent" href="javascript:void(0)"></a>');
					alink.text(j);
					alink.click(function(){
						var pointer = parseInt($(this).text());
						getFalconSearchEntity(keyword, lang,(pointer-1)*length,length,pointer);
					});
					navDiv.append(alink);
				}else{
					var span = $("<span class='navContent current' ></span>");
					span.text(j);
					navDiv.append(span);
				}
			}
			}
			if(currentPage<totalPage){
				var nextaLink = $('<a  class="navContent pnnav" href="javascript:void(0)"></a>');
				nextaLink.bind("click",function(){
					getFalconSearchEntity(keyword, lang,start+length,length,currentPage+1);
				});
				if(displayLang=='en')
					nextaLink.text("Next");
				else if(displayLang=="zh")
					nextaLink.text("下一页");
				navDiv.append(nextaLink);
			}	
			
		  }
	});
}

function hasRDFDesc(uri,box){
	var data = {};
	data["uri"] = uri;
	data["lang"] = displayLang;
	
	data = JSON.stringify(data);
	data = ("hasRDFDesc=" + encodeURIComponent(data));
	$.ajax({
		url: ENTSERV,
		async : false,
		data : data,
		dataType : "json",
		type : "post",
		success : function(result) {
			box.find(".wait").hide();
			box.find(".opBox input").attr("disabled",false);
			
			var flag = result.flag;
			if(flag=="invalid"){
				box.find(".invalid").show();
			}else{
				var container = box.find(".valid").show();
				container.html("");
				var header = $("<div class='header'></div>");
				container.append(header);
				if(displayLang=="en"){
					header.html("The uri you entered is:");
				}else if(displayLang=="zh"){
					header.html("你输入的 uri 为：");
				}
				var uriID = result.uriID;
				var uri = result.uri;
				var label = result.label;
				var typeArray =result.type;
				
				var rentity = $('<div class="rentity"></div>');
				container.append(rentity);
				var addOp = $("<span class='add-uri-op input'></span>");
				var addOplabel = $("<span></span>");
				addOp.append(addOplabel);
				addOp.attr("uid",uriID);
				if (displayLang == "en") {
					addOplabel.html("Add it");
				} else if (displayLang == "zh") {
					addOplabel.html("加入");
				}
				if($(".uriBox a[uid="+uriID+"]").length>0){
					addOp.addClass("disabled");
				}
				rentity.append(addOp);
				var titleDiv = $("<div class='title'></div>");
				rentity.append(titleDiv);
				var h3 = $("<h3></h3>");
				titleDiv.append(h3);
				var titleLink = $("<a target='_blank'></a>").html(label);
				var href = WEBAPP+"entity/o" + uriID+"?lang="+displayLang;
				titleLink.attr("href", href);
				titleLink.attr("title", uri);
				titleLink.attr("uid",uriID);
				h3.append(titleLink);

				if(typeArray.length>0){
					var typeBox = $("<div class='typeBox'><span class='pc'>is a</span></div>");
					rentity.append(typeBox);
					for (i = 0; i < typeArray.length; i++) {
						var typeItem = typeArray[i];
						var span = $("<span></span>");
						span.html(typeItem.label);
						span.attr("cid", typeItem.id);
						typeBox.append(span);
						if (i != typeArray.length - 1) {
							var label = $("<label> , </label>");
							typeBox.append(label);
						}
					}
				}
			}
		}
	});
}

function init() {
	if($(".container").length>0){
		if(Genre=="o"){
			var name;
			if (displayLang == "en") {
				name = "untitled";
			} else if (displayLang == "zh") {
				name = "未命名";
			}
			var etype = "-1";
			var eid = "-1";
			var gname = Gname;
			createEditEntityBox(name, etype, eid, gname,Etype, Eid);
			
		}else if(Genre=="e"){
			var name = $("#ename").val();
			var etype = Etype;
			var eid =Eid;
			var gname = Gname;
			createEditEntityBox(name, etype, eid, gname);	
		}
		
		
	    $(".recommendSection").tabs({
	    });
	    
	    recommend();
	    
	    $(".commentarea").change(function(){
	    	if(!$(this).hasClass("changed")){
	    		$(this).addClass("changed");
	    	}
	    });
	}
}

function isCreate(){
	var res = false;
	if($("#custom_type").val()=="create"){
		res = true;
	}
	return res;
}

function saveEntity(name, etype, eid, array,comment,imgAddArray,imgDelArray) {
	var result;
	var data = {};
	data["groupID"] = Gid;
	data["name"] = name;
	data["etype"] = etype;
	data["eid"] = eid;
	data["member"] = array;
	data["lang"] = displayLang;
	if(comment!=null){
		data["comment"] = comment;
	}
	if(imgAddArray.length>0){
		data["imgAdd"] = imgAddArray;
	}
	if(imgDelArray.length>0){
		data["imgDel"] = imgDelArray;
	}
	data["user"] = getUser();

	data = JSON.stringify(data);
	data = ("sventity=" + encodeURIComponent(data));

	$.ajax({
		url: ENTSERV,
		async : false,
		data : data,
		dataType : "json",
		type : "post",
		beforeSend:function(){
			var div = $("<div class='load-data2'></div>");
	   		$("body").append(div);	
		},
		success : function(data) {
			$("body").find(".load-data2").remove();
			result = data;
		}
	});
	return result;
}

function unselect(li) {
	li.find("span").remove();
	li.find("a").removeClass("nav-select");
}
